using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;

using log4net;
using System.Net;
using System.Threading;

namespace GTService
{
    public partial class Service1 : ServiceBase
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(Service1));

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            logger.Info("Started");

            this.jabberClient1.Server = global::GTService.Properties.Settings.Default.server;
            this.jabberClient1.User = global::GTService.Properties.Settings.Default.user;
            this.jabberClient1.Password = global::GTService.Properties.Settings.Default.pass;

            int icnt = 0;
            while (GetIPExternal() == null)
            {
                if (icnt > global::GTService.Properties.Settings.Default.cnt) return;

                logger.Info(string.Format("Waiting {0} ms", global::GTService.Properties.Settings.Default.sleep));
                Thread.Sleep(global::GTService.Properties.Settings.Default.sleep);

                icnt++;
            }

            this.jabberClient1.Connect();
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            logger.Info("Stoped");
        }

        private void jabberClient1_OnAfterPresenceOut(object sender, jabber.protocol.client.Presence pres)
        {
            logger.Info("OnAfterPresenceOut");
            logger.Info(pres.OuterXml);
        }

        private void jabberClient1_OnAuthenticate(object sender)
        {
            logger.Info("OnAuthenticate");
        }

        private void jabberClient1_OnAuthError(object sender, System.Xml.XmlElement rp)
        {
            logger.Info("OnAuthError");
            logger.Info(rp.OuterXml);
        }

        private void jabberClient1_OnBeforePresenceOut(object sender, jabber.protocol.client.Presence pres)
        {
            logger.Info("OnBeforePresenceOut");
            logger.Info(pres.OuterXml);
        }

        private void jabberClient1_OnConnect(object sender, jabber.connection.StanzaStream stream)
        {
            logger.Info("OnConnect");
            //logger.Info(stream.);
        }

        private void jabberClient1_OnDisconnect(object sender)
        {
            logger.Info("OnDisconnect");
        }

        private void jabberClient1_OnError(object sender, Exception ex)
        {
            logger.Info("OnError");
            logger.Info(ex.Message);
        }

        private bool jabberClient1_OnInvalidCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            logger.Info("OnInvalidCertificate");
            //logger.Info(sslPolicyErrors.);
            return default(bool);
        }

        private void jabberClient1_OnIQ(object sender, jabber.protocol.client.IQ iq)
        {
            logger.Info("OnIQ");
            logger.Info(iq.OuterXml);
        }

        private void jabberClient1_OnLoginRequired(object sender)
        {
            logger.Info("OnLoginRequired");
        }

        private void jabberClient1_OnMessage(object sender, jabber.protocol.client.Message msg)
        {
            logger.Info("OnMessage");
            logger.Info(msg.OuterXml);

            this.jabberClient1.Message("zloty50@gmail.com", msg.FirstChild.InnerText);
        }

        private void jabberClient1_OnPresence(object sender, jabber.protocol.client.Presence pres)
        {
            logger.Info("OnPresence");
            logger.Info(pres.OuterXml);
        }

        private void jabberClient1_OnProtocol(object sender, System.Xml.XmlElement rp)
        {
            logger.Info("OnProtocol");
            logger.Info(rp.OuterXml);
        }

        private void jabberClient1_OnReadText(object sender, string txt)
        {
            logger.Info("OnReadText");
            logger.Info(txt);
        }

        private void jabberClient1_OnRegistered(object sender, jabber.protocol.client.IQ iq)
        {
            logger.Info("OnRegistered");
            logger.Info(iq.OuterXml);
        }

        private bool jabberClient1_OnRegisterInfo(object sender, jabber.protocol.iq.Register register)
        {
            logger.Info("OnRegisterInfo");
            logger.Info(register.OuterXml);
            return default(bool);
        }

        private void jabberClient1_OnStreamError(object sender, System.Xml.XmlElement rp)
        {
            logger.Info("OnStreamError");
            logger.Info(rp.OuterXml);
        }

        private void jabberClient1_OnStreamHeader(object sender, System.Xml.XmlElement rp)
        {
            logger.Info("OnStreamHeader");
            logger.Info(rp.OuterXml);
        }

        private void jabberClient1_OnStreamInit(object sender, jabber.protocol.ElementStream stream)
        {
            logger.Info("OnStreamInit");
            //logger.Info(stream);
        }

        private void jabberClient1_OnWriteText(object sender, string txt)
        {
            logger.Info("OnWriteText");
            logger.Info(txt);
        }

        /**/

        private IPAddress GetIPExternal()
        {
            IWebProxy proxy = null;
            if (global::GTService.Properties.Settings.Default.proxy)
            {
                proxy = WebRequest.GetSystemWebProxy();
                proxy.Credentials = CredentialCache.DefaultCredentials;
            }

            WebClient wc = new WebClient();
            wc.Proxy = proxy;

            string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
            UTF8Encoding utf8 = new UTF8Encoding();
            string requestHtml = "";
            try
            {
                requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
                logger.Info(string.Format("External IP address is {0}", requestHtml));
            }
            catch (WebException we)
            {
                logger.Error("", we);
                return null;
            }

            IPAddress externalIp = IPAddress.Parse(requestHtml);
            return externalIp;
        }

    }
}
